<template>
  <div class="orders">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input 
            v-model="searchForm.orderNumber" 
            placeholder="请输入订单号" 
            clearable 
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input 
            v-model="searchForm.userId" 
            placeholder="请输入用户ID" 
            clearable 
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择订单状态" 
            clearable
            @change="handleSearch"
          >
            <el-option label="待付款" value="PENDING" />
            <el-option label="已付款" value="PAID" />
            <el-option label="已发货" value="SHIPPED" />
            <el-option label="已送达" value="DELIVERED" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      style="width: 100%"
      border
    >
      <el-table-column prop="orderNumber" label="订单号" width="180" />
      <el-table-column label="用户信息" width="150">
        <template #default="{ row }">
          <div v-if="row.user">
            <div>{{ row.username || row.user.username }}</div>
            <div style="font-size: 12px; color: #999;">ID: {{ row.userId }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" width="200">
        <template #default="{ row }">
          <div v-if="row.product">
            <div>{{ row.product.name }}</div>
            <div style="font-size: 12px; color: #999;">数量: {{ row.quantity }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="{ row }">
          ¥{{ row.totalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.orderStatus)">
            {{ getStatusText(row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentMethod" label="支付方式" width="120">
        <template #default="{ row }">
          {{ getPaymentMethodText(row.paymentMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="下单时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="250">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewDetails(row)">查看详情</el-button>
          <el-button type="warning" link @click="handleEditAddress(row)">修改地址</el-button>
          <el-button
            v-if="row.orderStatus === 'PAID'"
            type="success"
            link
            @click="handleShip(row)"
          >
            发货
          </el-button>
          <el-button
            v-if="row.orderStatus === 'PENDING'"
            type="danger"
            link
            @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder" class="order-details">
        <div class="details-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{ currentOrder.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.orderDate) }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(currentOrder.orderStatus)">
                {{ getStatusText(currentOrder.orderStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              {{ getPaymentMethodText(currentOrder.paymentMethod) }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              ¥{{ currentOrder.totalAmount.toFixed(2) }}
            </el-descriptions-item>
            <el-descriptions-item label="订单积分">
              {{ currentOrder.orderPoints }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="details-section">
          <h3>收货信息</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="联系电话">{{ currentOrder.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
            <el-descriptions-item label="运送方式">{{ getShippingMethodText(currentOrder.shippingMethod) }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentOrder.remarks || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="details-section">
          <h3>商品信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品名称">{{ currentOrder.product?.name }}</el-descriptions-item>
            <el-descriptions-item label="商品价格">¥{{ currentOrder.product?.price.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="购买数量">{{ currentOrder.quantity }}</el-descriptions-item>
            <el-descriptions-item label="商品积分">{{ currentOrder.product?.productPoints }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="details-section">
          <h3>用户信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ currentOrder.user?.username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentOrder.user?.email }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ currentOrder.user?.phone }}</el-descriptions-item>
            <el-descriptions-item label="积分">{{ currentOrder.user?.points }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改地址对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      title="修改收货地址"
      width="500px"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="100px"
      >
        <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="addressForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入完整的收货地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddressSubmit" :loading="submitting">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="运送方式" prop="shippingMethod">
          <el-select v-model="shipForm.shippingMethod" placeholder="请选择运送方式">
            <el-option label="快递" value="EXPRESS" />
            <el-option label="标准配送" value="STANDARD" />
            <el-option label="自提" value="PICKUP" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleShipSubmit" :loading="submitting">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getOrderList,
  getOrderDetails,
  updateOrderAddress,
  updateOrderStatus,
  shipOrder,
  cancelOrder
} from '@/api/admin'
import { Search } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  orderNumber: '',
  userId: '',
  status: ''
})

// 订单列表数据
const loading = ref(false)
const submitting = ref(false)
const orderList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 订单详情对话框
const detailsDialogVisible = ref(false)
const currentOrder = ref(null)

// 修改地址对话框
const addressDialogVisible = ref(false)
const addressFormRef = ref(null)
const addressForm = reactive({
  orderId: '',
  address: ''
})

// 发货对话框
const shipDialogVisible = ref(false)
const shipFormRef = ref(null)
const shipForm = reactive({
  orderId: '',
  shippingMethod: ''
})

// 表单验证规则
const addressRules = {
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

const shipRules = {
  shippingMethod: [
    { required: true, message: '请选择运送方式', trigger: 'change' }
  ]
}

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    if (searchForm.orderNumber) {
      params.orderNumber = searchForm.orderNumber
    }
    if (searchForm.userId) {
      params.userId = parseInt(searchForm.userId)
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    const res = await getOrderList(params)
    orderList.value = res.data.records || res.data
    total.value = res.data.total || res.data.length
  } catch (error) {
    console.error(error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadOrderList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrderList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrderList()
}

// 查看订单详情
const handleViewDetails = async (row) => {
  try {
    const res = await getOrderDetails(row.id)
    currentOrder.value = res.data
    detailsDialogVisible.value = true
  } catch (error) {
    console.error(error)
    ElMessage.error('获取订单详情失败')
  }
}

// 修改地址
const handleEditAddress = (row) => {
  addressForm.orderId = row.id
  addressForm.address = row.address
  addressDialogVisible.value = true
}

// 提交地址修改
const handleAddressSubmit = async () => {
  if (!addressFormRef.value) return
  
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await updateOrderAddress(addressForm.orderId, addressForm.address)
        ElMessage.success('地址修改成功')
        addressDialogVisible.value = false
        loadOrderList()
      } catch (error) {
        console.error(error)
        ElMessage.error('地址修改失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 发货
const handleShip = (row) => {
  shipForm.orderId = row.id
  shipForm.shippingMethod = ''
  shipDialogVisible.value = true
}

// 提交发货
const handleShipSubmit = async () => {
  if (!shipFormRef.value) return
  
  await shipFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await shipOrder(shipForm.orderId, shipForm.shippingMethod)
        ElMessage.success('发货成功')
        shipDialogVisible.value = false
        loadOrderList()
      } catch (error) {
        console.error(error)
        ElMessage.error('发货失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      type: 'warning'
    })
    await cancelOrder(row.id)
    ElMessage.success('订单已取消')
    loadOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 工具函数
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const getStatusType = (status) => {
  const types = {
    PENDING: 'warning',
    PAID: 'info',
    SHIPPED: 'primary',
    DELIVERED: 'success',
    COMPLETED: 'success',
    CANCELLED: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待付款',
    PAID: '已付款',
    SHIPPED: '已发货',
    DELIVERED: '已送达',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return texts[status] || status
}

const getPaymentMethodText = (method) => {
  const texts = {
    CASH: '现金',
    CREDIT_CARD: '信用卡',
    DEBIT_CARD: '借记卡',
    ALIPAY: '支付宝',
    WECHAT: '微信支付',
    BANK_TRANSFER: '银行转账'
  }
  return texts[method] || method
}

const getShippingMethodText = (method) => {
  const texts = {
    EXPRESS: '快递',
    STANDARD: '标准配送',
    PICKUP: '自提'
  }
  return texts[method] || method
}

onMounted(() => {
  loadOrderList()
})
</script>

<style scoped>
.orders {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.order-details {
  max-height: 600px;
  overflow-y: auto;
}

.details-section {
  margin-bottom: 30px;
}

.details-section h3 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}
</style> 